import { getDicts } from "@/api/system/crccode";

const state = {
  dictStatus: {}, // 字典加载状态
  dict: {}, // 字典数据
};

const mutations = {
  SET_DICT_STATUS: (state, { dictKey, status }) => {
    state.dictStatus[dictKey] = status;
  },
  SET_DICT: (state, { dictKey, data }) => {
    state.dict[dictKey] = data || [];
    state.dict = { ...state.dict };
  },
};

const actions = {
  getDict({ state, commit }, dictKey) {
    if (!dictKey) {
      return;
    }
    let searchKeys = [];
    // 寻找没有缓存字典列表的key
    const dictKeyArr = dictKey.split(",");
    for (let i = 0; i < dictKeyArr.length; i++) {
      const key = dictKeyArr[i];

      if (
        !state.dict[key]?.length &&
        (state.dictStatus[key] == undefined || state.dictStatus[key] == "faild")
      ) {
        searchKeys.push(key);
        // 设置某字典的请求状态为加载中
        commit("SET_DICT_STATUS", { dictKey: key, status: "loading" });
      }
    }

    if (!searchKeys?.length) {
      return;
    }

    const param = searchKeys.join(",");
    getDicts(param)
      .then((res) => {
        if (res.code == 200) {
          searchKeys.forEach((key) => {
            // 缓存字典
            commit("SET_DICT", { dictKey: key, data: res?.data[key] || [] });
            // 设置某字典的请求状态为加载完成
            commit("SET_DICT_STATUS", { dictKey: key, status: "completed" });
          });
        }
      })
      .catch((error) => {
        searchKeys.forEach((key) => {
          // 设置某字典的请求状态为加载失败
          commit("SET_DICT_STATUS", { dictKey: key, status: "faild" });
        });
      });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
